<template>
  <div class="app-container" v-loading="loading">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="72px"
    >
      <el-form-item :label="`${$branchName?$branchName:'分院'}名称`" prop="branchName">
        <el-input
          v-input-restrict
          v-model="queryParams.branchName"
          :placeholder="`请输入${$branchName?$branchName:'分院'}名称`"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          v-preventReClick
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button
          v-preventReClick
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-preventReClick
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <div>
      <div></div>
    </div>
    <!-- 管理员设置弹框 -->
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      title="管理员设置"
      :visible.sync="adminListOpen"
      width="80%"
      append-to-body
    >
      <el-button
        v-preventReClick
        type="primary"
        plain
        icon="el-icon-plus"
        size="mini"
        @click="handleAddAdmin"
        >添加管理员</el-button
      >
      <el-table
        v-loading="adminloading"
        style="margin-top: 20px"
        :data="adminList"
      >
        <el-table-column
          align="center"
          property="nickName"
          label="姓名"
        ></el-table-column>
        <el-table-column
          align="center"
          property="userName"
          label="账号"
        ></el-table-column>
        <el-table-column
          align="center"
          property="phoneNumber"
          label="手机号码"
        ></el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template slot-scope="scope">
            <!-- // 0.启用 1.禁用 2.待提交 3.待审核 4.已驳回 5.已到期 -->
            <el-tag type="success" v-if="scope.row.status == 0">启用</el-tag>
            <el-tag type="danger" v-if="scope.row.status == 1">禁用</el-tag>
            <el-tag v-if="scope.row.status == 2">待提交</el-tag>
            <el-tag type="warning" v-if="scope.row.status == 3">待审核</el-tag>
            <el-tag type="danger" v-if="scope.row.status == 4">已驳回</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              v-preventReClick
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleAdminUpdate(scope.row)"
              >编辑</el-button
            >
            <el-button
              v-preventReClick
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleAdminSwitch(scope.row)"
              >{{ scope.row.status == 0 ? "停用" : "启用" }}</el-button
            >
            <el-button
              v-preventReClick
              v-if="scope.row.status == 1"
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleAdminDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <!-- 添加编辑 管理员弹框 -->
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :title="addAdminTitle"
      :visible.sync="addAdminOpen"
      width="620px"
      append-to-body
    >
      <el-form
        ref="addAdminForm"
        :model="addAdminForm"
        :rules="addAdminRules"
        label-width="100px"
      >
        <el-form-item label="姓名" prop="nickName">
          <el-input
          v-input-restrict v-model="addAdminForm.nickName" placeholder="请输入名字" />
        </el-form-item>
        <el-form-item label="账号" prop="userName">
          <el-input
          v-input-restrict
            :disabled="addAdminTitle == `编辑${$branchName?$branchName:'分院'}管理员`"
            v-model="addAdminForm.userName"
            placeholder="请输入账号"
          />
        </el-form-item>
        <el-form-item label="手机号码" prop="phoneNumber">
          <el-input
          v-input-restrict
            :disabled="addAdminTitle == `编辑${$branchName?$branchName:'分院'}管理员`"
            v-model="addAdminForm.phoneNumber"
            placeholder="请输入手机号码"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-preventReClick @click="addAdminOpen = false"
        >取 消</el-button>
        <el-button
          v-preventReClick
          type="primary"
          @click="addAdminFormsubmitForm"
          >确 定</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改岗位对话框 -->
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :title="title"
      :visible.sync="open"
      width="1300px"
      append-to-body
    >
      <el-form @submit.native.prevent ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item :label="`${$branchName?$branchName:'分院'}名称`" prop="branchName">
              <el-input
          v-input-restrict
                show-word-limit
                maxlength="20"
                style="width: 80%"
                v-model="form.branchName"
                :placeholder="`请输入${$branchName?$branchName:'分院'}名称`"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人" prop="principal">
              <el-input
          v-input-restrict
                maxlength="10"
                style="width: 80%"
                v-model="form.principal"
                placeholder="请输入联系人"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="tel">
              <el-input
          v-input-restrict
                style="width: 80%"
                v-model="form.tel"
                placeholder="请输入手机号码"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地址" prop="address">
              <el-input
          v-input-restrict
                maxlength="20"
                style="width: 80%"
                v-model="form.address"
                placeholder="请输入地址"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="封面" prop="branchPic">
              <div class="flex">
                <!-- 上传图片 -->
                <div
                  v-if="form.branchPic"
                  class="upload-head"
                  @click="editCropper()"
                >
                  <img v-bind:src="form.branchPic" class="cover" />
                </div>
                <div v-else class="upload-head" @click="editCropper()">
                  <div>
                    <img src="@/assets/images/add.png" class="add" alt="" />
                  </div>
                  <div>上传图片</div>
                </div>

                <div class="uploadTip">
                  建议图片比例16:10，支持jpg、png格式，图片小于5M
                </div>
              </div>

              <vuecut
                :w="320"
                :h="200"
                :url="form.branchPic"
                @coverResult="coverResult"
                title="图片上传"
                :open.sync="vuecutshow"
              ></vuecut>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item :label="`${$branchName?$branchName:'分院'}简介`" prop="content">
              <el-input
          v-input-restrict
                style="width: 80%"
                maxlength="500"
                show-word-limit
                :autosize="{ minRows: 5, maxRows: 8 }"
                v-model="form.content"
                type="textarea"
                :placeholder="`请输入${$branchName?$branchName:'分院'}简介`"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-preventReClick @click="open = false">取 消</el-button>
        <el-button v-preventReClick type="primary" @click="submitForm"
          >确 定</el-button>
      </div>
    </el-dialog>
    <!-- 列表 -->
    <div class="list flex" v-infinite-scroll="getMore">
      <el-empty
        v-if="postList.length == 0"
        style="margin: 0 auto"
        :description="`暂无${$branchName?$branchName:'分院'}~`"
      ></el-empty>
      <div
        :style="{
          backgroundImage: `url('${item.branchPic?item.branchPic:require('@/assets/images/branch.png')}')`,
          backgroundSize: 'cover',
          backgroundRepeat: 'no-repeat',
        }"
        class="card rela shou"
        v-for="(item, index) in postList"
        :key="index"
        @click="toMajor(item)"
      >
        <div class="function abso" >
          <div class="iconbox" @click.stop="HandleAdmin(item)">
            <img
              class="shou"
              src="@/assets/images/strator_img.png"

            />
          </div>
          <div class="iconbox" @click.stop="handleUpdate(item)">
            <img
              class="shou"
              src="@/assets/images/icon2.png"

            />
          </div>
          <div class="iconbox"  @click.stop="handleDelete(item)">
            <img
              class="shou"
              src="@/assets/images/icon3.png"

            />
          </div>
        </div>
        <div class="bottom abso">
          <div class="content" style="white-space: pre-wrap">
            {{ item.content }}
          </div>
          <div class="t">{{ item.branchName }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  listPost_branch,
  getPost_branch,
  delPost_branch,
  addPost_branch,
  updatePost_branch,
  listPost_branchAdmin,
  addPost_branchAdmin,
  updatePost_branchAdmin,
} from "@/api/schoolOrganization/organization";
import { delUser, getUser, updateUser } from "@/api/system/user";
import { checkPhonenot } from "@/utils/validate";
export default {
  name: "Post",
  dicts: ["sys_normal_disable"],
  data() {
    return {
      adminList: [],
      adminListOpen: false,
      editAdminId: "",
      editBranchId: "",
      addAdminTitle: "添加管理员",
      addAdminOpen: false,
      addAdminForm: {
        userId: undefined,
        nickName: undefined,
        phoneNumber: undefined,
        userName: undefined,
        roleIds: undefined,
      },
      addAdminRules: {
        nickName: [
          { required: true, message: "姓名不能为空", trigger: "blur" },
        ],
        userName: [
          { required: true, message: "账号不能为空", trigger: "blur" },
        ],
        phoneNumber: [{ required: false, validator: checkPhonenot, trigger: "blur" }],
      },
      vuecutshow: false,
      // 遮罩层
      loading: false,
      adminloading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 总页数
      totalPage: 0,
      // 岗位表格数据
      postList: [],
      upLoadData: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // level
      level: [],
      // 查询参数
      activeIndex: "",
      queryParams: {
        pageNum: 1,
        pageSize: 12,
        branchName: undefined,
        schoolId: undefined,
      },
      // 表单参数
      form: {
        schoolId: undefined,
        branchId: undefined,
        branchName: undefined,
        branchPic: undefined,
        address: undefined,
        content: undefined,
        principal: undefined,
        tel: undefined,
      },
      // 表单校验
      rules: {
        branchName: [
          { required: true, message: `${this.$branchName?this.$branchName:'分院'}名称不能为空`, trigger: "blur" },
        ],
        content: [{ required: true, message: "简介不能为空", trigger: "blur" }],
        tel: [{ required: false, validator: checkPhonenot, trigger: "blur" }],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getMore() {
      this.upLoadData = [];
      if (this.postList.length >= this.total) {
        console.log("没有更多");
      } else {
        this.queryParams.pageNum++;
        if (this.queryParams.pageNum > this.totalPage) {
          console.log("没有更多了");
          return;
        }
        this.getList(true);
      }
    },
    resetAddAdmin() {
      this.form = {
        userId: undefined,
        nickName: undefined,
        phoneNumber: undefined,
        userName: undefined,
        roleIds: undefined,
      };
      this.resetForm("addAdminForm");
    },

    /* 去专业管理页面 */
    toMajor(row) {
      this.$router.push({
        path: "/schoolOrganization/major",
        query: {
          branchId: row.branchId,
          branchName: row.branchName,
        },
      });
    },
    /** 组件返回图片 */
    coverResult(e) {
      this.form.branchPic = e;
    },
    editCropper() {
      this.vuecutshow = true;
    },
    // 状态选择 查询列表
    handleSelect(key, keyPath) {
      this.queryParams.status = key;
      this.getList();
    },
    /** 查询岗位列表 */
    getList(num) {
      if (!num) {
        this.queryParams = {
          pageNum: 1,
          pageSize: 12,
        };
        this.postList = [];
      }
      this.loading = true;
      listPost_branch(this.queryParams).then((response) => {
        if (num) {
          this.upLoadData = response.rows;
          this.postList = this.postList.concat(this.upLoadData);
        } else {
          this.postList = response.rows;
        }
        console.log(this.postList,'this.postList')
        this.total = response.total;
        //向上取整 总页数
        this.totalPage = Math.ceil(response.total / this.queryParams.pageSize);
        this.loading = false;
      });
    },
    // 表单重置
    reset() {
      this.form = {
        schoolId: undefined,
        branchId: undefined,
        branchName: undefined,
        branchPic: undefined,
        address: undefined,
        content: undefined,
        principal: undefined,
        tel: undefined,
      };
      this.resetForm("form");
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.form.schoolId = this.$store.getters.schoolId;
      this.title = `添加${this.$branchName?this.$branchName:'分院'}`;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const postId = row.branchId || this.ids;
      getPost_branch(postId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = `修改${this.$branchName?this.$branchName:'分院'}`;
      });
    },
    addAdminFormsubmitForm: function () {
      this.$refs["addAdminForm"].validate((valid) => {
        console.log(valid);
        if (valid) {
          if (this.addAdminTitle == `编辑${this.$branchName?this.$branchName:'分院'}管理员`) {
            updateUser(this.addAdminForm).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.addAdminOpen = false;
              this.getAdminList();
            });
          } else {
            this.addAdminForm.roleIds = [9];
            this.addAdminForm.schoolId = this.$store.getters.schoolId;
            this.addAdminForm.branchId = this.editBranchId;
            addPost_branchAdmin(this.addAdminForm).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.addAdminOpen = false;
              this.getAdminList();
            });
          }
        }
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: "正在处理…",
            spinner: "el-icon-loading",
            background: "rgba(255, 255, 255, 0.6)",
          });
          if (this.form.branchId != undefined) {
            updatePost_branch(this.form)
              .then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
                loading.close();
              })
              .catch(() => {
                loading.close();
              });
          } else {
            addPost_branch(this.form)
              .then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
                loading.close();
              })
              .catch(() => {
                loading.close();
              });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const branchId = row.branchId || this.ids;
      this.$modal
        .confirm(`确定删除分院【${row.branchName}】？`)
        .then(function () {
          return delPost_branch(branchId);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /*  管理员设置*/
    async HandleAdmin(row) {
      this.adminListOpen = true;
      this.editBranchId = row.branchId;
      this.getAdminList();
    },
    async getAdminList() {
      this.adminloading = true;
      let res = await listPost_branchAdmin({ branchId: this.editBranchId });
      this.adminList = res.rows;
      this.adminloading = false;
    },
    /* 添加管理员 */
    handleAddAdmin() {
      this.addAdminTitle = `添加${this.$branchName?this.$branchName:'分院'}管理员`;
      this.addAdminOpen = true;
      this.resetAddAdmin();
    },
    /** 修改管理员 */
    async handleAdminUpdate(row) {
      this.addAdminTitle = `编辑${this.$branchName?this.$branchName:'分院'}管理员`;
      this.addAdminOpen = true;
      this.resetAddAdmin();
      let res = await getUser(row.userId);
      this.addAdminForm = res.data;
      this.addAdminForm.roleIds = res.roleIds;
    },
    // 删除管理员
    handleAdminDelete(row) {
      this.$confirm(`确定删除吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delUser(row.userId).then((res) => {
            this.$modal.msgSuccess("操作成功");
            this.open = false;
            this.getAdminList();
          });
        })
        .catch(() => {});
    },
    // 停用 启用管理员
    handleAdminSwitch(row) {
      this.$confirm(`确定${row.status == 0 ? "停用" : "启用"}吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let data = JSON.parse(JSON.stringify(row));
          data.status = row.status == 0 ? 1 : 0;
          getUser(data.userId).then((res) => {
            data.roleIds = res.roleIds;
            updateUser(data).then((response) => {
              this.$modal.msgSuccess("操作成功");
              this.open = false;
              this.getAdminList();
            });
          });
        })
        .catch(() => {});
    },
  },
};
</script>
<style scoped lang="scss">
.list {
  max-height: calc(100vh - 220px);
  overflow-y: scroll;
  margin-top: 16px;

  .card:hover {
    .function {
      display: flex;
    }

    .bottom {
      .content {
        display: -webkit-box;
      }
    }
  }

  .card {
    overflow: hidden;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    width: 340px;
    height: 220px;
    border-radius: 4px;
    margin: 0 40px 40px 0;

    .function {
      display: none;
      border-radius: 0px 4px 0px 4px;
      padding: 0 8px 0 8px;
      right: 0;
      top: 0;
      border-radius: 0px 4px, 0px, 4px;
      background: rgba(0, 0, 0, 0.3);
     .iconbox{
        padding: 5px 6px 5px 6px;
     }
      img {
        width: 16px;
        height: 16px;
      }
    }

    .bottom {
      bottom: 0;

      .content {
        text-overflow: -o-ellipsis-lastline;
        overflow: hidden; //溢出内容隐藏
        text-overflow: ellipsis; //文本溢出部分用省略号表示
        display: none; //特别显示模式
        -webkit-line-clamp:8; //行数
        line-clamp: 8;
        -webkit-box-orient: vertical; //盒子中内容竖直排列
        width: 340px;
        box-sizing: border-box;
        background: rgba(0, 0, 0, 0.3);
        padding: 2px 12px;
        font-size: 10px;
        font-weight: 400;
        color: rgba(255, 255, 255, 1);
      }

      .t {
        text-align: center;
        font-size: 16px;
        font-weight: 400;
        line-height: 40px;
        color: rgba(255, 255, 255, 1);
        width: 340px;
        height: 40px;
        border-radius: 0px 0px, 4px, 4px;
        background: rgba(35, 184, 112, 1);
      }
    }
  }
}

// 上传图片样式
.uploadTip {
  margin-left: 5px;
  font-size: 12px;
  font-weight: 400;
  color: rgba(166, 166, 166, 1);
  line-height: 210px;
  height: 150px;
}

.upload-head {
  cursor: pointer;
  position: relative;
  display: inline-block;
  width: 172px;
  height: 112px;
  border-radius: 4px;
  border: 1px dashed rgba(184, 196, 209, 1);

  .add {
    width: 29px;
    height: 29px;
    margin: 25px auto 0 auto;
  }

  div {
    font-size: 14px;
    font-weight: 400;
    color: rgba(153, 153, 153, 1);
    margin-top: 0px;
    width: 100%;
    text-align: center;
  }

  .cover {
    width: 170px;
    height: 110px;
    border-radius: 4px;
  }
}
</style>
